#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
LIS系统依赖安装脚本
自动检测Python版本并安装必要的依赖包
"""

import sys
import subprocess
import platform
import os
from pathlib import Path

def check_python_version():
    """检查Python版本"""
    version = sys.version_info
    print(f"Python版本: {version.major}.{version.minor}.{version.micro}")
    
    if version < (3, 8):
        print("❌ 错误: Python版本必须 >= 3.8")
        print(f"当前版本: {version.major}.{version.minor}.{version.micro}")
        return False
    
    print("✅ Python版本检查通过")
    return True

def check_pip():
    """检查pip是否可用"""
    try:
        subprocess.run([sys.executable, "-m", "pip", "--version"], 
                      check=True, capture_output=True)
        print("✅ pip检查通过")
        return True
    except (subprocess.CalledProcessError, FileNotFoundError):
        print("❌ 错误: pip不可用")
        return False

def upgrade_pip():
    """升级pip"""
    print("🔄 正在升级pip...")
    try:
        subprocess.run([sys.executable, "-m", "pip", "install", "--upgrade", "pip"], 
                      check=True)
        print("✅ pip升级完成")
        return True
    except subprocess.CalledProcessError as e:
        print(f"❌ pip升级失败: {e}")
        return False

def install_requirements(requirements_file):
    """安装依赖包"""
    if not os.path.exists(requirements_file):
        print(f"❌ 错误: 找不到文件 {requirements_file}")
        return False
    
    print(f"🔄 正在安装依赖包 (从 {requirements_file})...")
    try:
        subprocess.run([sys.executable, "-m", "pip", "install", "-r", requirements_file], 
                      check=True)
        print("✅ 依赖包安装完成")
        return True
    except subprocess.CalledProcessError as e:
        print(f"❌ 依赖包安装失败: {e}")
        return False

def check_system_info():
    """检查系统信息"""
    print(f"操作系统: {platform.system()} {platform.release()}")
    print(f"架构: {platform.machine()}")
    print(f"Python路径: {sys.executable}")

def check_fonts():
    """检查中文字体"""
    print("\n🔍 检查中文字体...")
    
    if platform.system() == "Windows":
        font_paths = [
            "C:/Windows/Fonts/simsun.ttc",
            "C:/Windows/Fonts/simsun.ttf",
            "C:/Windows/Fonts/simhei.ttf",
            "C:/Windows/Fonts/msyh.ttf",
            "C:/Windows/Fonts/simkai.ttf"
        ]
        
        found_fonts = []
        for font_path in font_paths:
            if os.path.exists(font_path):
                found_fonts.append(os.path.basename(font_path))
        
        if found_fonts:
            print(f"✅ 找到中文字体: {', '.join(found_fonts)}")
        else:
            print("⚠️ 警告: 未找到常见的中文字体文件")
            print("PDF导出功能可能无法正确显示中文")
    else:
        print("ℹ️ 非Windows系统，请确保安装了中文字体")

def test_imports():
    """测试关键模块导入"""
    print("\n🧪 测试关键模块导入...")
    
    test_modules = [
        ("PyQt6", "PyQt6"),
        ("pandas", "pandas"),
        ("openpyxl", "openpyxl"),
        ("reportlab", "reportlab"),
        ("PIL", "Pillow"),
        ("cryptography", "cryptography"),
        ("psutil", "psutil")
    ]
    
    failed_imports = []
    
    for module_name, package_name in test_modules:
        try:
            __import__(module_name)
            print(f"✅ {package_name} 导入成功")
        except ImportError:
            print(f"❌ {package_name} 导入失败")
            failed_imports.append(package_name)
    
    if failed_imports:
        print(f"\n⚠️ 以下模块导入失败: {', '.join(failed_imports)}")
        print("请检查安装是否成功")
        return False
    else:
        print("✅ 所有关键模块导入成功")
        return True

def main():
    """主函数"""
    print("=" * 60)
    print("LIS系统 - 依赖安装脚本")
    print("=" * 60)
    
    # 检查系统信息
    check_system_info()
    print()
    
    # 检查Python版本
    if not check_python_version():
        sys.exit(1)
    
    # 检查pip
    if not check_pip():
        sys.exit(1)
    
    # 升级pip
    upgrade_pip()
    
    # 检查字体
    check_fonts()
    
    # 选择安装模式
    print("\n📦 选择安装模式:")
    print("1. 生产环境 (仅核心依赖)")
    print("2. 开发环境 (包含测试工具)")
    print("3. 完整安装 (所有依赖)")
    
    while True:
        choice = input("\n请选择 (1/2/3): ").strip()
        if choice in ['1', '2', '3']:
            break
        print("❌ 无效选择，请输入 1、2 或 3")
    
    # 安装依赖
    if choice == '1':
        requirements_file = "requirements_production.txt"
        print("\n🚀 安装生产环境依赖...")
    elif choice == '2':
        requirements_file = "requirements_dev.txt"
        print("\n🚀 安装开发环境依赖...")
    else:
        requirements_file = "requirements.txt"
        print("\n🚀 安装完整依赖...")
    
    if not install_requirements(requirements_file):
        sys.exit(1)
    
    # 测试导入
    if not test_imports():
        print("\n⚠️ 部分模块导入失败，请检查安装")
        sys.exit(1)
    
    print("\n" + "=" * 60)
    print("✅ 依赖安装完成！")
    print("=" * 60)
    print("\n📋 下一步:")
    print("1. 运行主程序: python scripts/main.py")
    print("2. 运行测试: python -m pytest test/")
    print("3. 查看文档: 阅读 README.md")
    
    if choice in ['2', '3']:
        print("\n🛠️ 开发工具:")
        print("- 代码格式化: black src/")
        print("- 代码检查: flake8 src/")
        print("- 类型检查: mypy src/")

if __name__ == "__main__":
    main()
